"use strict";
/**
 * 员工选择器
 * 依赖 jquery.ztree.all.min.js 插件
 */
;(function ($, window, document, undefined) {
    let oTree = function (ele, options) {
        this.$element = $(ele) //主元素
        this.defaults = {
            all: false, //人物组织都开启
            search: true, //支持搜索
            text: '#field-dept', //文本框id 用于取值
            range: '', //范围
            other: '', //其他属性配置
            boxId: ''
        }
        this.settings = $.extend({}, this.defaults, options)
    };
    let saveVal = []; //操作以保存的值， 数组形式
    let allJson; //从后台获取原始组织架构数据，防止多次加载
    let filterDataList //数据结构进行处理
    let orgZTree //可以多方位操作ztree
    oTree.prototype = {
        dialog: function () {
            let that = this, treeWrapper, allLoadData
            $.ajaxSettings.async = false
            let fun = this.settings.type === 'materialType'?'getTypeInfo':'getStaffInfo'
            $.getJSON(root + 'control/adIndex.html?cla=examine&fun='+fun).done(function (data) {
                allJson = data
                filterDataList = that.filterDataSloveList(data)
                // 页面进入渲染
                that.getValue(that.settings.boxId)
                if (that.settings.all) {
                    //全部开启
                    allLoadData = that.dataSolve(data) //进行数据处理
                }
            })
            if (!allJson || allJson === '') {
                warn('获取组织架构失败')
                return false
            }
            //第一个loading隐藏
            $('.search-loading').css('display', 'none')
            treeWrapper = $('.multi-staff').find('.multi-staff-left-cnt-list')
            let zTreeWrap = treeWrapper.find('#ztreeArea')
            //判断搜索是否开启
            if (that.settings.search) {
                that.searchFuc(filterDataList)
            }
            if (that.settings.all === true) {
                //全部开启
                that.loadAll(zTreeWrap, allLoadData)
            }
            $('#confirm-staff').on('click', function () {
                const boxId = $(this).data('boxid')
                that.renderOut(saveVal, boxId)
                $('#examineOrgTree').hide()
            })

            $('#confirm-material').on('click', function () {
                const boxId = $(this).data('boxid')
                that.renderOut(saveVal, boxId)
                $('#examineMaterialTypeTree').hide()
            })
        }, filterDataSloveList: function (data) {
            let that = this
            let treeNode = that.dataSolve(data)
            let filterResult = []

            function filterTree(fNode, dataNode) {
                dataNode.forEach(function (aData) {
                    fNode.push({
                        id: aData.id, name: aData.name, type: aData.type, crumbs: aData.crumbs
                    })
                    if (aData.children) {
                        filterTree(fNode, aData.children)
                    }
                })
            }

            filterTree(filterResult, treeNode)

            function unique(arr) {
                let ret = []
                for (let i = 0, j = arr.length; i < j; i++) {
                    if (ret.indexOf(arr[i].id) === -1) {
                        ret.push(arr[i])
                    }
                }
                return ret
            }

            return unique(filterResult)
        }, loadAll: function (ele, data) {
            let that = this
            let $ele = $(ele)
            let showIcon = this.settings.type === 'materialType'?false:true
            orgZTree = $.fn.zTree.init($ele, {
                view: {
                    dblClickExpand: false, selectedMulti: false, showLine: false,showIcon: showIcon,
                    addHoverDom: addHoverDom, removeHoverDom: removeHoverDom, addDiyDom: addDiyDom
                }, callback: {
                    onClick: function (event, treeId, treeNode, clickFlag) {
                        //物料分类单选
                        if(that.settings.type === 'materialType') {
                            saveVal = []
                        }
                        //获取对应的id或者name值，只需treeNode.id 或者 treeNode.name 即可
                        let repIndex //获取重复数组的索引
                        let aObj = $("#" + treeNode.tId + "-a")
                        let checkIcon = aObj.find('.jstree-custom-checked')
                        if (checkIcon.hasClass('selected')) {
                            checkIcon.removeClass('selected')
                        } else {
                            checkIcon.addClass('selected')
                        }
                        if (saveVal.length > 0) {
                            for (let i = 0; i < saveVal.length; i++) {
                                if (saveVal[i].id === treeNode.id) {
                                    repIndex = i
                                }
                            }
                        }
                        if (repIndex) {
                            //点击之后 当前项与已选择部门 有重复
                            saveVal.splice(repIndex, 1)
                        } else {
                            if (repIndex === 0) {
                                //因为 splice从1开始， 而索引是从0开始,所以第一个元素特殊处理
                                saveVal.splice(repIndex, 1)
                            } else {
                                saveVal.push({
                                    id: treeNode.id,
                                    name: treeNode.name,
                                    crumbs: treeNode.crumbs,
                                    type: treeNode.type, // icon: treeNode.icon
                                })
                            }
                        }
                        // 判断范围
                        if (that.settings.range === 'staff' && treeNode.type !== 'staff') {
                            warn('请选择员工')
                            return false
                        } else if (that.settings.range === 'job' && treeNode.type !== 'job') {
                            warn('请选择职位')
                            return false
                        } else {
                            //以数组形式返回选种值
                            that.renderNode(saveVal)
                            that.deleteNode(saveVal)
                        }
                    }
                }
            }, data)

            //ztree 鼠标经过添加&删除 效果
            function addHoverDom(treeId, treeNode) {
                let pObj = $('#' + treeNode.tId)
                pObj.children('.jstree-wholerow').addClass('jstree-wholerow-hover')
            }

            function removeHoverDom(treeId, treeNode) {
                $('.ztree .jstree-wholerow').removeClass('jstree-wholerow-hover')
            }

            //添加自定义div
            function addDiyDom(treeId, treeNode) {
                let aObj = $('#' + treeNode.tId + '-a');
                if ($('#diyBtn-' + treeNode.id).length > 0) return
                const selectedStr = '<div class="jstree-custom-checked"></div>';
                let hoverStr = '<div class="jstree-wholerow"></div>';
                let pObj = $('#' + treeNode.tId);
                pObj.prepend(hoverStr)
                aObj.append(selectedStr)
                pObj.find('.jstree-wholerow').eq(0).bind('click', function () {
                    //物料分类单选
                    if(that.settings.type === 'materialType') {
                        saveVal = []
                    }
                    //获取对应的id或者name值，只需treeNode.id 或者 treeNode.name 即可
                    let repIndex, //获取重复数组的索引
                        aObj = $("#" + treeNode.tId + "-a"), checkIcon = aObj.find('.jstree-custom-checked')
                    if (checkIcon.hasClass('selected')) {
                        checkIcon.removeClass('selected')
                    } else {
                        checkIcon.addClass('selected')
                    }
                    if (saveVal.length > 0) {
                        for (let i = 0; i < saveVal.length; i++) {
                            if (saveVal[i].id === treeNode.id) {
                                repIndex = i
                            }
                        }
                    }
                    if (repIndex) {
                        saveVal.splice(repIndex, 1)
                    } else {
                        if (repIndex === 0) {
                            saveVal.splice(repIndex, 1)
                        } else {
                            saveVal.push({
                                id: treeNode.id,
                                name: treeNode.name,
                                crumbs: treeNode.crumbs,
                                type: treeNode.type, // icon: treeNode.icon
                            })
                        }
                    }
                    // 判断范围
                    if (that.settings.range === 'staff' && treeNode.type !== 'staff') {
                        warn('请选择到员工')
                        return false
                    } else if (that.settings.range === 'job' && treeNode.type !== 'job') {
                        warn('请选择到职位')
                        return false
                    } else {
                        //以数组形式返回选种值
                        that.renderNode(saveVal)
                        that.deleteNode(saveVal)
                    }
                })
                for (let i = 0; i < saveVal.length; i++) {
                    if (treeNode.id === saveVal[i].id) {
                        aObj.find('.jstree-custom-checked').addClass('selected')
                    }
                }
            }

            //渲染已选中部门
            if (saveVal && saveVal.length > 0) {
                that.renderNode(saveVal)
                that.deleteNode(saveVal)
            }
        }, searchFuc: function (data) {
            let that = this
            $('.multi-staff').addClass('multi-staff-WithSearch')
            let placeholder = that.settings.type === 'materialType'?'搜索分类':'搜索成员或部门'
            let sdom = `
            <div class="multi-staff-search-wrapper">
                <div class="multi-staff-search">
                    <span class="ww-searchInput">
                    <span class="ww-commonImg ww-commonImg-Search ww-searchInput-icon" href="javascript:"></span>
                    <span class="ww-commonImg ww-commonImg-ClearText ww-searchInput-delete" id="clearMemberSearchInput"></span>
                    <input type="text" id="memberSearchInput" class="qui-inputText ww-inputText ww-searchInput-text" placeholder="`+placeholder+`"></span>
                </div>
                <div id="searchResult" class="ww-searchResult" style="display: none">
                    <div id="search-member-list-title" class="ww-searchResult-title ww-searchResult-title-First">搜索结果</div>
                    <div class="search-member-none">无搜索结果...</div>
                    <ul id="search-member-list"></ul>
                </div>
            </div>`;
            $('.multi-staff-left-cnt').prepend(sdom)
            let $input = $('#memberSearchInput');
            //聚焦失焦样式
            $input.focus(function () {
                $(this).addClass('onfocus')
            }).blur(function () {
                $(this).removeClass('onfocus')
            })
            $input.on('keydown', function (event) {
                event.stopPropagation()
            }).on('keyup', function (event) {
                let inputValue = $(this).val();
                inputValue = inputValue.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
                let matcher = new RegExp(inputValue, "i");
                let filterTxt = $.grep(data, function (value) {
                    return matcher.test(value.name)
                });
                if (inputValue) {
                    $('#clearMemberSearchInput').show()
                    $('#searchResult').show()
                    $('#partyTree').hide()
                    const searchList = $('#search-member-list')
                    searchList.empty()
                    let resultList = '';
                    filterTxt.forEach(function (data) {
                        resultList += `<li data-id="${data.id}" data-name="${data.name}" title="${data.crumbs}" data-type="${data.type}"><i class="ww-commonImg ww-commonImg-TreeMenuThumb"></i>${data.name}</li>`
                    })
                    //判断筛选之后有没有值
                    if (resultList) {
                        $('.search-member-none').hide()
                    } else {
                        $('.search-member-none').show()
                    }
                    searchList.append(resultList)
                    //清空
                    const searchInputDel = $('.ww-searchInput-delete')
                    searchInputDel.show()
                    searchInputDel.on('click', function () {
                        $('#memberSearchInput').val(null)
                        $('#searchResult').hide()
                        $('#partyTree').show()
                        $('#search-member-list').empty()
                        $('.search-member-none').show()
                        $(this).hide()
                    })
                    $('#search-member-list li').on('click', function () {
                        //物料分类单选
                        if(that.settings.type === 'materialType') {
                            saveVal = []
                        }
                        let selectId = $(this).attr('data-id'), selectName = $(this).attr('data-name'),
                            selectCrumbs = $(this).attr('title'), selectType = $(this).attr('type'), repInx //获取重复数组的索引
                        if (saveVal.length > 0) {
                            for (let i = 0; i < saveVal.length; i++) {
                                if (saveVal[i].name === selectName) {
                                    repInx = i
                                }
                            }
                        }
                        if (repInx) {
                            saveVal.splice(repInx, 1)
                        } else {
                            if (repInx === 0) {
                                saveVal.splice(repInx, 1)
                            } else {
                                saveVal.push({
                                    id: selectId, name: selectName, crumbs: selectCrumbs, type: selectType
                                })
                            }
                        }
                        $('#searchResult').hide()
                        $('#partyTree').show()
                        $('#search-member-list').empty()
                        $('#memberSearchInput').val(null)
                        $('#clearMemberSearchInput').hide()
                        if (saveVal.length > 0) {
                            $('.multi-staff-right-no-result').hide()
                        } else {
                            $('.multi-staff-right-no-result').show()
                        }
                        //以数组形式返回选种值
                        that.renderNode(saveVal)
                        that.deleteNode(saveVal)
                        //ztree进行操作，点击li之后 展开树
                        const selectedTreeNode = orgZTree.getNodeByParam("id", selectId);
                        //处理ztree数 的选中图标
                        let aObj = $("#" + selectedTreeNode.tId + "-a");
                        let checkIcon = aObj.find('.jstree-custom-checked');
                        if (checkIcon.hasClass('selected')) {
                            checkIcon.removeClass('selected')
                        } else {
                            checkIcon.addClass('selected')
                        }
                        orgZTree.selectNode(selectedTreeNode, true) //指定选中ID的节点
                        orgZTree.expandNode(selectedTreeNode, true, false) //指定选中ID节点展开
                        // orgZTree.cancelSelectedNode()  //ztree取消选中
                    })
                } else {
                    $('#searchResult').hide()
                    $('#partyTree').show()
                    $('#search-member-list').empty()
                    $('#clearMemberSearchInput').hide()
                    $('.search-member-none').show()
                }
            })
        }, // 数据处理
        dataSolve: function (data) {
            let memberData = data.data;
            let zTreeNode = [];

            // 暂时不支持拼音
            function fillNode(zNode, dataNode, presentName) {
                dataNode.forEach(function (aDate) {
                    let thisNode = {
                        id: aDate.id,
                        name: aDate.deptname,
                        type: aDate.type,
                        parentId: aDate.parent_id,
                        crumbs: presentName + '/' + aDate.deptname,
                        children: []
                    };
                    let noChildNode = {
                        id: aDate.id,
                        name: aDate.deptname,
                        type: aDate.type,
                        parentId: aDate.parent_id,
                        crumbs: presentName + '/' + aDate.deptname,
                    };
                    if (aDate.children.length > 0) {
                        zNode.push(thisNode)
                    } else {
                        zNode.push(noChildNode)
                    }
                    fillNode(thisNode.children, aDate.children, thisNode.crumbs)
                })
            }

            fillNode(zTreeNode, memberData, '')

            function format(str) {
                if (str) {
                    return str.toLowerCase()
                }
                return ''
            }

            //排序
            function compare(propertyName) {
                return function (object1, object2) {
                    const value1 = object1[propertyName];
                    const value2 = object2[propertyName];
                    if (value2 < value1) {
                        return 1
                    } else if (value2 > value1) {
                        return -1
                    } else {
                        return 0
                    }
                }
            }

            return zTreeNode
        }, getValue: function (boxId = '') {
            let that = this, obj, savedVal = [], filterJson = []
            obj = $('#' + that.settings.text)
            if (obj) {
                savedVal = obj.val().split(';')
            }
            for (let i = 0; i < savedVal.length; i++) {
                (function (i) {
                    filterDataList.forEach(function (item, index) {
                        if (that.settings.range === 'staff' && item.type !== 'staff') {

                        } else if (that.settings.range === 'job' && item.type !== 'job') {

                        } else if (item.id === savedVal[i]) {
                            return filterJson.push(item)
                        }
                    })
                })(i)
            }
            saveVal = filterJson
            that.renderOut(saveVal, boxId)
            return saveVal
        }, outRepair: function () {
            let that = this
            $(document).on('click', '.js-disselect-party', function () {
                $(this).parent().remove()
                saveVal = that.savedJson()
                if (saveVal.length > 0) {
                    $('.js-show-party-selector').html('修改')
                } else {
                    $('.js-show-party-selector').html('添加')
                }
            })
        }, savedJson: function () {
            let that = this, itemList = $('.js-party-select-result-list').children('div'), saveLength = itemList.length,
                jsonList = [], outInputVal = ''
            if (saveLength > 0) {
                itemList.each(function (index, ele) {
                    jsonList.push({
                        name: $(ele).find('.parydata').attr('data-name'),
                        id: $(ele).find('.parydata').attr('data-id'),
                        crumbs: $(ele).find('.parydata').attr('data-crumbs')
                    })
                    outInputVal += $(ele).find('.parydata').attr('data-id') + ';'
                })
            }
            //渲染外部input的值
            $('#' + that.settings.text).val(outInputVal)
            return jsonList
        }, renderOut: function (array, boxId) {
            let that = this, wrap = '', perVal = '', staffName = ''
            let jsResultList
            if (boxId && boxId.length >0) {
                jsResultList = $('[data-box="' + boxId + '"]').find('.js-party-select-result-list')
            } else {
                jsResultList = $('.js-party-select-result-list')
            }
            jsResultList.html('')
            if (array.length > 0) {
                array.map(function (ele, index) {
                    // 返回时判断
                    if (that.settings.range === 'staff' && ele.type !== 'staff') {

                    } else if (that.settings.other === 'selector') {
                        perVal += ele.id + ';'
                        wrap += `<span class="choose-part-value li-ico">${ele.name}</span><a data-stid="${ele.id}" data-boxid="${boxId}" onclick='del_staff(this)' href='javascript:void(0)'><div><span class='u-icon-delete'><i></i></span></div></a>`
                        staffName += ele.name + ';'
                    } else {
                        perVal += ele.id + ';'
                        wrap += `<span>${ele.name}</span>` + '，'
                        staffName += ele.name + ';'
                    }
                })
                wrap = wrap.substring(0, wrap.length - 1)

                $('.js-show-party-selector').html('修改')
            } else {
                $('.js-show-party-selector').html('添加')
            }
            jsResultList.append(wrap)
            //渲染外部input的值
            const settingText = $('#' + that.settings.text)
            //物料分类选择
            if(settingText.siblings('[name="typeName"]').length>0){
                settingText.siblings('[name="typeName"]').val(staffName.split(";").join(""))
                perVal = perVal.split(";").join("");
            }
            settingText.val(perVal)
            // 判断是否有staffName,用于显示
            if (settingText.next('[name="staffName[]"]')) {
                settingText.next('[name="staffName[]"]').val(staffName)
            }
        }, renderNode: function (array) {
            let that = this, liHtml = ''
            const saveNode = $('#saveNode')
            saveNode.html('')
            if (array.length > 0) {
                $('.multi-staff-right-no-result').hide()
            } else {
                $('.multi-staff-right-no-result').show()
            }
            array.forEach(item => {
                // 判断是否有可选范围
                if (that.settings.range === 'staff' && item.type !== 'staff') {
                    liHtml += ''
                }else if (that.settings.range === 'job' && item.type !== 'job') {
                    liHtml += ''
                } else {
                    // 选中 增加到候选
                    liHtml += `
                    <li title="${item.crumbs}" data-name="${item.name}" data-id="${item.id}" data-type="${item.type}" class="ww-menuDialog-DualCols-colRight-cnt-item token-input-token js-list-item">
                        <span class="ww-commonImg icon icon-folder-blue"></span>
                        <span class="ww-treeMenu-item-text" title="${item.crumbs}">${item.name}</span>
                        <a href="javascript:" class="ww-menuDialog-DualCols-colRight-cnt-item-delete">
                            <span class="ww-commonImg ww-commonImg-DeleteItem js-delete"></span>
                        </a>
                    </li>`
                }
            });
            saveNode.append(liHtml)
        }, deleteNode: function (arr) {
            let arrNode = arr;
            $('.js-list-item').on('click', function () {
                const curId = $(this).attr('data-id'); //获取当前ID
                for (let i = 0; i < arrNode.length; i++) {
                    if (arrNode[i].id === curId) {
                        arrNode.splice(i, 1)
                    }
                }
                //删除选中树节点的选中图标
                const selectedTreeNode = orgZTree.getNodeByParam("id", curId);
                const aObj = $("#" + selectedTreeNode.tId + "-a");
                const checkIcon = aObj.find('.jstree-custom-checked');
                checkIcon.removeClass('selected')
                //操作接下来的逻辑
                $(this).remove()
                saveVal = arrNode
                if (saveVal.length > 0) {
                    $('.multi-staff-right-no-result').hide()
                } else {
                    $('.multi-staff-right-no-result').show()
                }
                return saveVal
            })
        }, init: function () {
            this.dialog()
            this.outRepair()
        }
    }
    $.fn.orgTree = function (opts) {
        const ot = new oTree(this, opts); //接收两个参数，主元素 + 设置参数 this: 使用这个插件的容器  opts: 外部配置
        return ot.init()
    }
})(jQuery, window, document)
